package com.cn.music.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.cn.music.MainActivity;
import com.cn.music.R;
import com.cn.music.databinding.ActivityLoginBinding;
import com.cn.music.view.LoginViewModel;

public class LoginActivity extends AppCompatActivity {

    private ActivityLoginBinding binding;
    private LoginViewModel loginModel;
    private String phone;
    private String password;
    private final static String TAG = "登录页面";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        loginModel = new ViewModelProvider(this).get(LoginViewModel.class);
        toRegister();
        login();
    }

    private void login() {
        binding.btnLogin.setOnClickListener(v -> {
            phone = binding.phoneInput.getText().toString();
            password = binding.passwordInput.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                Toast.makeText(this,R.string.phone_input,Toast.LENGTH_SHORT).show();
            }if (TextUtils.isEmpty(password)) {
                Toast.makeText(this,R.string.password_input,Toast.LENGTH_SHORT).show();
            }if (phone.length() != 11){
                Toast.makeText(this,"请输入有效手机号码",Toast.LENGTH_SHORT).show();
            } else {
                loginModel.loadLoginModel(phone, password).observe(this, loginModels -> {
                    if (loginModels.get(0).getCode() == 200) {
                        Toast.makeText(this,"登录成功",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("uid", loginModels.get(0).getAccount().getId()+"");
                        startActivity(intent);
                    } else {
                        Toast.makeText(this,"登录失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }

    private void toRegister() {
        binding.toRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this,RegisterActivity.class);
            startActivity(intent);
        });
    }

}
